using System;
using System.IO;
using System.Configuration;

namespace WebDavSyncTool
{
    public static class Logger
    {
        public enum LogLevel
        {
            Error = 0,
            Info = 1
        }

        private static readonly string LogDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
        private static readonly object LogLock = new object();
        private static LogLevel currentLogLevel;

        static Logger()
        {
            if (!Directory.Exists(LogDirectory))
            {
                Directory.CreateDirectory(LogDirectory);
            }

            // 从配置文件读取日志级别
            string logLevel = ConfigurationManager.AppSettings["LogLevel"] ?? "Error";
            currentLogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), logLevel, true);
        }

        private static void WriteLog(string level, string message)
        {
            string logFile = Path.Combine(LogDirectory, string.Format("{0:yyyy-MM-dd}.log", DateTime.Now));
            string logMessage = string.Format("{0:yyyy-MM-dd HH:mm:ss} [{1}] {2}", 
                DateTime.Now, 
                level, 
                message);

            lock (LogLock)
            {
                File.AppendAllText(logFile, logMessage + Environment.NewLine, System.Text.Encoding.UTF8);
            }
        }

        public static void LogInfo(string message)
        {
            if (currentLogLevel >= LogLevel.Info)
            {
                WriteLog("INFO", message);
            }
        }

        public static void LogError(string message, Exception ex = null)
        {
            // 错误日志总是记录
            WriteLog("ERROR", message);
            if (ex != null)
            {
                WriteLog("ERROR", string.Format("异常详情: {0}\n{1}", ex.Message, ex.StackTrace));
            }
        }

        public static void RefreshLogLevel()
        {
            string logLevel = ConfigurationManager.AppSettings["LogLevel"] ?? "Error";
            currentLogLevel = (LogLevel)Enum.Parse(typeof(LogLevel), logLevel, true);
        }
    }
} 